package se.lth.student.axisandroidcam.server;

import se.lth.cs.fakecamera.Axis211A;
import se.lth.cs.fakecamera.MotionDetector;
import se.lth.student.axisandroidcam.client.Toolbox;

public class CameraThread extends Thread {
	private Axis211A fakeCamera;
	private byte[] imageBuffer;
	private int bufferLength;
	private MotionDetector motion;
	private boolean hasMotion;
	
	
	
	public CameraThread(){
		fakeCamera = new Axis211A();
		imageBuffer = new byte[Axis211A.IMAGE_BUFFER_SIZE];		
		motion = new MotionDetector();
	}
	
	
	public void run(){		
		Toolbox.printDebug("CameraThread started");
		boolean isConnected;
		do{
			isConnected =fakeCamera.connect();
		}while(!isConnected);	
		Toolbox.printDebug("Fake camera connected");
		while(true){
			try {
				Thread.sleep(40);
				fetchNewImage();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
								
		}
		
	}
	
	private synchronized void fetchNewImage(){
		imageBuffer = new byte[Axis211A.IMAGE_BUFFER_SIZE];	
		bufferLength = fakeCamera.getJPEG(imageBuffer, 0);		
		hasMotion = motion.detect();
	}
	
	public synchronized boolean hasMotion(){
		return hasMotion;
	}
	
	public synchronized int getImageLength(){
		return bufferLength;
	}
	
	public synchronized byte[] getImage(){
		return imageBuffer;		
	}

}
